package com.leetcode.search.dfs;

/**
 * @author Dennis Li
 * @date 2020/7/26 11:30
 */
public class NumIslands_200 {

    private final int[][] directions = {{1, 0}, {-1, 0}, {0, -1}, {0, 1}};

    public int numIslands(char[][] grid) {
        if (grid.length == 0 || grid[0].length == 0) return 0;
        int width = grid[0].length, high = grid.length;
        int times = 0;
        for (int i = 0; i < high; i++) {
            for (int j = 0; j < width; j++) {
                if (grid[i][j] == '1') {
                    dfs(grid, i, j);
                    times++;
                }
            }
        }
        return times;
    }

    public void dfs(char[][] grid, int a, int b) {
        grid[a][b] = '0';
        for (int[] d : directions) {
            int y = a + d[0], x = b + d[1];
            if (y >= 0 && y < grid.length && x >= 0 && x < grid[0].length && grid[y][x] == '1') {
                dfs(grid, y, x);
            }
        }
    }

}
